import {
  asyncRoutes,
  constantRoutes
} from '@/router'
import {
  getUserMenu,
  getUserButton
} from "../../api/user"
import Layout from '@/layout'
/**
 * Use meta.role to determine if the current user has permission
 * 使用 meta.role 来确定当前用户是否具有权限
 * @param roles
 * @param route
 */
// function hasPermission(roles, route) {
//   if (route.meta && route.meta.roles) {
//     return roles.some(role => route.meta.roles.includes(role))
//   } else {
//     return true
//   }
// }


/**
 * Filter asynchronous routing tables by recursion
 * 通过递归过滤异步路由表
 * @param routes asyncRoutes
 * @param roles
 */
// export function filterAsyncRoutes(routes, roles) {
//   const res = [];                 // 生成好的菜单数组
//   var check = new RegExp('MP');   // 检查项，过滤掉小程序菜单
//   routes.forEach(route => {
//     const tmp = Object.assign({
//       children: []
//     }, {
//       ...route
//     })
//     //console.log(tmp);
//     // 如果不是小程序菜单时则添加；否则跳过当前项
//     if(!check.test(tmp.id))
//     {
//       // 如果当前数据包含子级菜单数据时则对子级菜单进行遍历
//       if (tmp.list) {
//         tmp.children = filterAsyncRoutes(tmp.list, roles)
//       }
//       // 如果当前数据的 parentId 为 0 则添加为一级菜单；否则添加为二级菜单
//       if (tmp.parentId === "0") {
//         res.push({
//           path: tmp.jump,
//           component: Layout,
//           name: tmp.name,
//           meta: {
//             title: tmp.title,
//             icon: tmp.icon
//           },
//           alwaysShow: true,
//           children: tmp.children
//         })
//       } else {
//         console.log("问题");
//         //console.log(tmp);
//         res.push({
//           path: tmp.jump,
//           component: require(`@/views/${tmp.component}`).default,
//           name: tmp.name,
//           meta: {
//             title: tmp.title,
//             icon: tmp.icon
//           },
//           hidden: tmp.hidden !== "false",
//           id: tmp.id
//         })
//       }
//       console.log(tmp);
//     }
//   })
//   return res
// }


/**
 * 遍历生成树形菜单
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = [];                 // 生成好的菜单数组
  var check = new RegExp('MP');   // 检查项，过滤掉小程序菜单
  routes.forEach(route => {
    const tmp = Object.assign({
      children: []
    }, {
      ...route
    })
    //console.log(tmp);
    // 如果不是小程序菜单时则添加；否则跳过当前项
    if(!check.test(tmp.id))
    {
      // 如果当前数据包含子级菜单数据时则对子级菜单进行遍历
      if (tmp.list) {
        tmp.children = filterAsyncRoutes(tmp.list, roles)
      }
      // 如果当前数据的 parentId 为 0 则添加为一级菜单；否则添加为二级菜单
      if (tmp.parentId === "0") {
        res.push({
          path: tmp.jump,
          component: Layout,
          name: tmp.name,
          meta: {
            title: tmp.title,
            icon: tmp.icon
          },
          alwaysShow: true,
          children: filterAsyncSonRoutes(tmp.list, roles, tmp.id)
        })
      }
    }
  })
  //console.log(res);
  return res;
}


/**
 * 遍历生成二级菜单
 * @param routes 一级菜单的子级list
 * @param roles 角色ID
 * @param parentId 所属菜单ID
 */
export function filterAsyncSonRoutes(routes, roles, parentId) {
  // console.log('遍历子菜单');
  // console.log(routes);
  // console.log(parentId);
  const res = [];                 // 生成好的菜单数组
  var btnRes = [];                // 生成好的按钮数组
  var check = new RegExp('MP');   // 检查项，过滤掉小程序菜单
  routes.forEach(route => {
    var tmp = Object.assign({
      children: []
    }, {
      ...route
    })
    //console.log(tmp);
    // 如果不是小程序菜单时则添加；否则跳过当前项
    if(!check.test(tmp.id))
    {
      if(tmp.parentId === parentId)
      {
        res.push({
          path: tmp.jump,
          component: require(`@/views/${tmp.component}`).default,
          name: tmp.name,
          meta: {
            title: tmp.title,
            icon: tmp.icon
          }
          //hidden: tmp.hidden !== "false",
          // id: tmp.id
        })

        // 生成菜单按钮缓存
        getUserButton(tmp.id).then(response => {
          // 如果按钮权限数据大于0时则添加
          if(response.data.result.length > 0)
          {
            // 遍历添加为数组
            response.data.result.forEach(item => {
              //console.log(item);
              if(item.parentId === tmp.id && item.view != "")
              {
                btnRes.push({
                  path: item.url,
                  component: require(`@/views/${item.view}`).default,
                  name: item.name,
                  meta: {
                    title: item.name,
                    icon: item.icon
                  },
                  hidden: item.isHidden !== "false",
                  id: item.id
                });
              }
            });
            // 将数据源存至临时缓存
            localStorage.setItem(tmp.name, JSON.stringify(btnRes));

            // // (测试) 查看已生成的数据
            // btnRes = JSON.parse(localStorage.getItem(tmp.name));
            // console.log(tmp.name);
            // console.log(btnRes);

            // 清空临时数组，便于下次循环使用
            btnRes.splice(0, btnRes.length);
          }
        });
      }
    }
    //console.log(tmp);
  });
  return res;
}


const state = {
  routes: [],
  addRoutes: [],
  btnList: []
}


const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_BUTTONLIST: (state, list) => {
    state.btnList = list
  },
}


const actions = {
  // 获取菜单权限
  generateRoutes({
    commit
  }, roles) {
    return new Promise(resolve => {
      let accessedRoutes;
      // 走云菜单
      // if (roles.includes('21')) {
      //   accessedRoutes = asyncRoutes || []
      //   commit('SET_ROUTES', accessedRoutes)
      //   resolve(accessedRoutes)
      // } else {
      //   getUserMenu().then(response => {
      //     const {
      //       data
      //     } = response;
      //     accessedRoutes = filterAsyncRoutes(data, roles)
      //     commit('SET_ROUTES', accessedRoutes)
      //     resolve(accessedRoutes)
      //   })
      // }

      getUserMenu().then(response => {
        const {
          data
        } = response;
        // 将数据源存至临时缓存
        localStorage.setItem('ALL_USERMENU', JSON.stringify(data));
        accessedRoutes = filterAsyncRoutes(data, roles);
        console.log(accessedRoutes);
        accessedRoutes = asyncRoutes || [];
        console.log(accessedRoutes);
        commit('SET_ROUTES', accessedRoutes);
        resolve(accessedRoutes);
      })

      // 走本地菜单
      // commit('SET_ROUTES', accessedRoutes)
      // resolve(accessedRoutes)
    })
  },
  // 获取按钮权限
  setButtonList({
    commit
  }, list) {
    commit('SET_BUTTONLIST', list)
  }
}


export default {
  namespaced: true,
  state,
  mutations,
  actions
}
